﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ChatServer
{
    class Client
    {
        Socket socket;
        Thread thread;
        byte[] data = new byte[1024];

        public Client(Socket s)
        {
            socket = s;
            Thread thread = new Thread(ReceiveMessage);
            thread.Start();
        }

        public void ReceiveMessage()
        {
            while (true)
            {
                if (socket.Poll(10, SelectMode.SelectRead))
                {
                    socket.Close();
                    return;
                }
                int length = socket.Receive(data);
                string message = Encoding.UTF8.GetString(data, 0, length);
                Program.BroadcastMessage(message);
                Console.WriteLine("接收到客户端的消息:" + message);
            }
        }

        public void SendMessages(string message)
        {
            socket.Send(Encoding.UTF8.GetBytes(message));
        }

        public bool IsConnected
        {
            get { return socket.Connected; }
        }
    }
}
